#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;

class LRUListNode
{
public:
    LRUListNode *next;
    bool empty;
    int key;
};

class LRUCache
{

public:
    LRUListNode *head, *tail;
    unordered_map<int, pair<int, LRUListNode *>> content;
    LRUCache(int capacity)
    {
        LRUListNode *s, *last = NULL;
        for (int i = 0; i < capacity; ++i)
        {
            s = new LRUListNode();
            s->empty = true;
            if (i == 0)
                head = s;
            if (i == capacity - 1)
                tail = s;
            if (last != NULL)
                last->next = s;
            last = s;
        }
    }

    int get(int key)
    {
        if (!content.count(key))
            return -1;
        else
        {
            auto p = content[key];
            int value = p.first;
            LRUListNode *s = p.second;
            if (head->next != NULL && (s == NULL || s->next != tail))
            {
                LRUListNode *t;
                if (s == NULL)
                {
                    t = head;
                    head = head->next;
                    content[head->key].second = NULL;
                }
                else
                {
                    t = s->next;
                    content[t->next->key].second = content[t->key].second;
                    s->next = s->next->next;
                }
                content[key].second = tail;
                tail->next = t;
                t->next = NULL;
                tail = t;
            }
            return value;
        }
    }

    void put(int key, int value)
    {
        if (content.count(key))
        {
            content[key].first = value;
            get(key);
            return;
        }
        if (head->empty)
        {
            head->empty = false;
        }
        else
        {
            content.erase(head->key);
        }
        head->key = key;
        content[key] = {value, tail};
        LRUListNode *s = head;
        if (head->next != NULL)
        {
            head = head->next;
            tail->next = s;
            s->next = NULL;
            tail = s;
        }
        else
            content[key].second = NULL;
        content[head->key].second = NULL;
    }
};

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache* obj = new LRUCache(capacity);
 * int param_1 = obj->get(key);
 * obj->put(key,value);
 */